/*
 * Design_Assignment_5.c
 *
 * Created: 4/22/2015 9:19:38 PM
 *  Author: Clinton
 */ 
#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define BAUDRATE 9600
#include "avr/interrupt.h"
#define BAUD_PRESCALER (F_CPU/(BAUDRATE*16UL) - 1 )
//Operating Mode: Asynchronous Normal mode for the UBRRn value

void USART_INIT(void)
{
	// This function will set the micro controller for serial communication with the PC
	// It sets the necessary baud rate registers, and prescaler value.
	UBRR0H = (uint8_t)(BAUD_PRESCALER >> 8);
	UBRR0L = (uint8_t)(BAUD_PRESCALER);
	UCSR0B = (1 << RXEN0) | (1 << TXEN0);
	UCSR0C = (3 << UCSZ00);
}
void USART_SEND(unsigned char data)
{
	// Function to send data from the ATmega328P to the terminal on the PC
	while(!(UCSR0A & (1 << UDRE0)));
	UDR0 = data;
}
unsigned char USART_RECEIVE(void)
{
	// This function receives data from the PC Terminal through
	// the USB cable.
	while(!(UCSR0A & (1<<RXC0)));
	return UDR0;
}

unsigned char Change_case(unsigned char letter)
{
	// Function to change the case of the received character
	// Example: if an a was received, the function will return an A
	// Example: if an A was received, the function will return an a
	unsigned char temp;
	if(letter & 32)
	{
		temp = letter - 32;  //If 32nd bit is 1, it was a lower case letter
	}
	else
	{
		temp = letter + 32; //If 32nd bit is 0, it was an upper case letter
	}
	return temp;               // Return the converted ASCII char.
}

unsigned char keyboard;    //char variable to represent button pressed on keyboard

int main(void)
{
	DDRB = 0xFF;								// port D is an output port
	TCCR1A = 0x82;								//clears OCR1A on compare match
	TCCR1B = 0x1A;								//Phase Correct PWM, inverted, N = 64
	ICR1 = 19999;							
	
	TCCR0A = 0xF3;				//fast pwm mode OCR0A = Top
	TCCR0B = 0x0B;				// prescaler = 1, fast pwm
	OCR0A = 0x3E;				//load top value
	OCR0B = 0x1F;				// start at 0% duty cycle

	
	
	//TIMSK1 = (1<<OCIE1B);
	//sei ();
	
	ADCSRA = 0x87;					//enable adc, prescaler = 128
	ADMUX = 0x47;					// 5.0V External Reference, Left Adjust = off, using ADC7
	
	USART_INIT();        //Call the USART initialization code
	while(1)
	{
		while(1)
		{
			ADCSRA |= (1<<ADSC);			// start conversion
			while((ADCSRA&(1<<ADIF))==0);
		
		if(ADC == 5)
			OCR1A = 490;
		else	
			OCR1A = 2160;	
		}
		return 0;
		
	}
}

ISR (TIMER1_COMPB_vect)
{
	int num = ADC*.0049;  //10mv / 1.1v steps
	char buf[4];
	itoa(num, buf, 10);  //converts binary to string
	
	unsigned char str[25] = "The Voltage Reading Is...";
	unsigned char strLenght = 25;
	int i = 0;
	
	for(i = 0; i< strLenght;i++)
		USART_SEND(str[i]);
		
	for(i = 0; i< 4;i++)
		USART_SEND(buf[i]);
	
	USART_SEND('\t');

	//USART_SEND('\n');
	//reset compare value if counter goes above threshold
}